package com.mo.axion.handler.handler;

import com.mo.axion.common.domain.AnchorInfo;
import com.mo.axion.common.domain.RecallTaskInfo;
import com.mo.axion.common.domain.TaskInfo;
import com.mo.axion.common.enums.AnchorState;
import com.mo.axion.handler.flowcontrol.FlowControlFactory;
import com.mo.axion.handler.flowcontrol.FlowControlParam;
import com.mo.axion.support.utils.LogUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.PostConstruct;
import java.util.Objects;

/**
 * @author Mo
 * @createTime 2024/2/23 15:44
 * @description 下发渠道handler基类
 */
@Slf4j
public abstract class BaseHandler implements Handler {
    /**
     * 标识渠道的code
     * 在子类初始化的时候指定
     */
    protected Integer channelCode;

    /**
     * 限流参数
     */
    protected FlowControlParam flowControlParam;

    @Autowired
    private FlowControlFactory flowControlFactory;

    @Autowired
    private HandlerHolder handlerHolder;

    @Autowired
    private LogUtils logUtils;


    @PostConstruct
    private void init() {
        handlerHolder.putHandler(channelCode, this);
    }

    /**
     * 处理下发任务 真正的下发接口 不同处理器实现不同渠道的下发服务
     * @param taskInfo 下发消息
     */
    @Override
    public void doHandler(TaskInfo taskInfo) {
        if (Objects.nonNull(flowControlParam)) {
            flowControlFactory.flowControl(taskInfo, flowControlParam);
        }
        if (handler(taskInfo)) {
            log.info("BaseHandler#doHandler方法 参数:{}", taskInfo);
            logUtils.print(
                    AnchorInfo.builder()
                    .state(AnchorState.SEND_SUCCESS.getCode())
                    .bizId(taskInfo.getBizId())
                    .messageId(taskInfo.getMessageId())
                    .businessId(taskInfo.getBusinessId())
                    .idList(taskInfo.getReceiver()).build()
            );
            return;
        }
        //  发送失败
        logUtils.print(
                AnchorInfo.builder()
                        .state(AnchorState.SEND_FAIL.getCode())
                        .bizId(taskInfo.getBizId())
                        .messageId(taskInfo.getMessageId())
                        .businessId(taskInfo.getBusinessId())
                        .idList(taskInfo.getReceiver()).build()
        );
    }

    /**
     * 统一处理handler接口
     * @param taskInfo
     * @return
     */
    public abstract boolean handler(TaskInfo taskInfo);
}
